package com.ztc.util.handle;

import com.aqgj.util.JsonWrapper;
import com.ztc.util.exceptions.BusinessException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.HashMap;


@ControllerAdvice
public class GlobalExceptionHandler {

	private final Logger log = LogManager.getLogger(GlobalExceptionHandler.class);

	@ExceptionHandler(MissingServletRequestParameterException.class)
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public HashMap<String, Object> defaultErrorHandler(MissingServletRequestParameterException ex) throws Exception {
		log.error(ex.getMessage(), ex);
		return JsonWrapper.failureWrapperMsg("请求参数错误");
	}

	@ExceptionHandler(TypeMismatchException.class)
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public HashMap<String, Object> defaultErrorHandler(TypeMismatchException ex) throws Exception {
		log.error(ex.getMessage(), ex);
		return JsonWrapper.failureWrapperMsg("请求参数类型转换失败");
	}


	@ExceptionHandler(NoHandlerFoundException.class)
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public HashMap<String, Object> defaultErrorHandler(NoHandlerFoundException ex) throws Exception {
		log.error(ex.getMessage(), ex);
		return JsonWrapper.failureWrapperMsg("请求接口不存在");
	}

	@ExceptionHandler(BusinessException.class)
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public HashMap<String, Object> defaultErrorHandler(BusinessException ex) throws Exception {
		log.error(ex.getMessage(), ex);
		return JsonWrapper.failureWrapperMsg(ex.getMessage());
	}

	@ExceptionHandler(Exception.class)
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public HashMap<String, Object> handleException(Exception ex) throws Exception{
		log.error(ex.getMessage(), ex);
		return JsonWrapper.failureWrapperMsg("系统错误，请联系管理员！");
	}
}
